//
//  LXFListeningKeyboard.m
//  Fshop
//
//  Created by 陈学明 on 17/1/4.
//  Copyright © 2017年 com.onloon. All rights reserved.
//

#import "LXFListeningKeyboard.h"

@implementation LXFListeningKeyboard
static LXFListeningKeyboard *listeningKeyboardObj = nil;
+(LXFListeningKeyboard *)isShowKeyboard{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        listeningKeyboardObj = [[LXFListeningKeyboard alloc]init];
        //监听键盘的弹起和收回
        [[NSNotificationCenter defaultCenter] addObserver:listeningKeyboardObj selector:@selector(listeningKeyBoarEvent:) name:UIKeyboardWillChangeFrameNotification object:nil];
    });
    return listeningKeyboardObj;
}

-(void)listeningKeyBoarEvent:(NSNotification *)not{
    
    UIView *firstView = [self findFirstResponder];
    if (firstView) {
        CGFloat time = 0.25;
        CGFloat keyStopPointY = [not.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].origin.y;
        //文本
        CGFloat textFieldPointY = 0;
        //相对于当前视图的位置
        CGRect rect = [self.view convertRect:firstView.bounds fromView:firstView];
        if (firstView) {
            textFieldPointY = CGRectGetMaxY(rect);
        }
        if (keyStopPointY!=0 && keyStopPointY < textFieldPointY) {
            [UIView animateWithDuration:time animations:^{
                self.view.frame = CGRectMake(0,keyStopPointY - textFieldPointY - 50, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            }];
        }else{
            [UIView animateWithDuration:time animations:^{
                self.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            }];
        }
    }
}

-(void)addKeyBoarNot{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listeningKeyBoarEvent:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
-(void)removeKeyboardNot{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (UIView *)findFirstResponder
{
    for (UIView *view in self.responders) {
        if (view.isFirstResponder) {
            return view;
        }
    }
    return nil;
}

-(void)setView:(UIView *)view{
   
    if (_view) {
        [_view endEditing:YES];
        _view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    }

    _view = view;
}
@end
